﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace SocialApi.TestApp.ViewModels
{
    public class DelegateCommand : ICommand
    {
        #region Implementation of ICommand

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        #endregion

        #region Настройки

        private readonly Action<object> _execute;

        private readonly Predicate<object> _canExecute;

        /// <summary>
        /// Создаёт новый экземпляр класса <see cref="DelegateCommand"/>
        /// </summary>
        /// <param name="execute">Действи выполнения</param>
        public DelegateCommand(Action<object> execute)
            : this(execute, null) { }

        /// <summary>
        /// Создаёт новый экземпляр класса <see cref="DelegateCommand"/>
        /// </summary>
        /// <param name="execute">Действи выполнения</param>
        /// <param name="canExecute">Событие, при которое возбудит <see cref="execute"/></param>
        public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion
    }
}